package com.java.controller.api;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.java.exceptioin.Assert;
import com.java.pojo.entity.UserInfo;
import com.java.pojo.vo.LoginVo;
import com.java.pojo.vo.RegisterVo;
import com.java.pojo.vo.UserIndexVo;
import com.java.pojo.vo.UserInfoVo;
import com.java.result.ResponseEnum;
import com.java.result.Result;
import com.java.service.UserAccountService;
import com.java.service.UserInfoService;
import com.java.utils.JwtUtils;
import com.java.utils.RegexValidateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * <p>
 * 用户基本信息 前端控制器
 * </p>
 *
 * @author Helen
 * @since 2021-07-08
 */

@Api("用户信息")
@RestController
@RequestMapping("/api/core/userInfo")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private UserAccountService userAccountService;

    @Resource
    private DefaultKaptcha defaultKaptcha;


    @ApiOperation("校验手机号")
    @PostMapping("/checkPhone/{phone}")
    public Boolean checkPhone(@PathVariable String phone){
        return userInfoService.ckPhone(phone);
    }


    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result register(@RequestBody RegisterVo registerVo){
        userInfoService.register(registerVo);
        return Result.ok("注册成功");
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result register(@RequestBody LoginVo loginVo, HttpServletRequest request){

        //需要实时记录登录日志
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        String verify = loginVo.getVerify();
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(password,ResponseEnum.PASSWORD_NULL_ERROR);
        Assert.notEmpty(verify,ResponseEnum.CODE_NULL_ERROR);
        boolean cellphone = RegexValidateUtils.checkCellphone(mobile);
        Assert.isTrue(cellphone,ResponseEnum.MOBILE_ERROR);
        String ip = request.getRemoteAddr();
        UserInfoVo userInfoVo = userInfoService.login(loginVo,ip);
        return Result.ok(userInfoVo);
    }

    @ApiOperation(value = "校验token")
    @GetMapping(value = "/checkToken")
    public Result checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean checkToken = JwtUtils.checkToken(token);
        if(checkToken){
            return Result.ok().message("校验成功");
        }else{
            return Result.fail().message("校验失败");
        }
    }


    //获取用户的绑定状态
    @ApiOperation("获取用户的绑定状态")
    @GetMapping("/getBindStatus")
    public Result getBindStatus(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        Integer status = userInfoService.getBindStatus(userId);
        return Result.ok(status);
    }

    //用户中心
    @ApiOperation("用户中心")
    @GetMapping("/getUserCenter")
    public Result getUserCenter(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        UserIndexVo userIndexVo = userInfoService.getUserCenter(userId);
        return Result.ok(userIndexVo);
    }


    @ApiOperation(value = "验证码")
    @GetMapping(value = "/captcha",produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        // 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        //-------------------生成验证码 begin --------------------------
        //获取验证码文本内容
        String text = defaultKaptcha.createText();
        UserInfo.VERIFY = text;
        System.out.println("验证码内容："+text);
        //将验证码文本内容放入session
        request.getSession().setAttribute("captcha",text);
        //根据文本验证码内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //输出流输出图片，格式为jpg
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null!=outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //-------------------生成验证码 end --------------------------
    }
}

